package com.example.archive.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.archive.entity.User;
import com.example.archive.mapper.UserMapper;
import com.example.archive.service.UserService;
import com.example.archive.service.SystemLogService;
import com.example.archive.util.Result;
import com.example.archive.dto.LoginResponseDto;
import com.example.archive.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.List;
import java.util.Objects;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    
    @Autowired
    private SystemLogService systemLogService;

    @Override
    public Result<Boolean> register(User user) {
        // 检查用户名是否已存在
        QueryWrapper<User> query = new QueryWrapper<>();
        query.eq("username", user.getUsername());
        if (userMapper.selectOne(query) != null) {
            return Result.fail(400, "用户名已存在");
        }
        // 密码加密（简单MD5，生产建议加盐）
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        // 角色默认为普通用户
        user.setRole("普通员工");
        return userMapper.insert(user) > 0 ? Result.success(true) : Result.fail(500, "注册失败");
    }

    @Override
    public Result<LoginResponseDto> login(String username, String password) {
        QueryWrapper<User> query = new QueryWrapper<>();
        query.eq("username", username)
             .eq("password", DigestUtils.md5DigestAsHex(password.getBytes()));
        User user = userMapper.selectOne(query);

        if (user != null) {
            // Check user status
            if (!"启用".equals(user.getStatus())) {
                return Result.fail(400, "账号已禁用");
            }
            // Generate a token
            String token = UUID.randomUUID().toString();
            // Store token in Redis with user ID as value and set expiration time (e.g., 30 minutes)
            stringRedisTemplate.opsForValue().set("login:" + token, String.valueOf(user.getUserId()), 30, java.util.concurrent.TimeUnit.MINUTES);
            // Set userId in UserContext
            UserContext.setUserId(user.getUserId());
            
            // 记录登录日志
            systemLogService.recordLog(user.getUserId(), "登录", "用户登录系统");
            
            // Create DTO and return
            LoginResponseDto loginResponseDto = new LoginResponseDto(user, token);
            return Result.success(loginResponseDto);
        } else {
            return Result.fail(400, "用户名或密码错误");
        }
    }

    @Override
    public Result<Boolean> logout(String token) {
        if (token != null && !token.isEmpty()) {
            // 获取用户ID用于记录日志
            String userIdStr = stringRedisTemplate.opsForValue().get("login:" + token);
            Integer userId = null;
            if (userIdStr != null) {
                try {
                    userId = Integer.valueOf(userIdStr);
                } catch (NumberFormatException e) {
                    // 忽略转换错误
                }
            }
            
            Boolean deleted = stringRedisTemplate.delete("login:" + token);
            
            // 记录登出日志
            if (userId != null) {
                systemLogService.recordLog(userId, "登出", "用户退出系统");
            }
            
            return Result.success(deleted != null && deleted);
        }
        return Result.fail(400, "Token is missing or invalid");
    }

    @Override
    public Result<List<User>> listUsers(String search) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (search != null && !search.isEmpty()) {
            queryWrapper.like("username", search).or().like("name", search);
        }
        List<User> users = userMapper.selectList(queryWrapper);
        return Result.success(users);
    }

    @Override
    public Result<Boolean> addUser(User user) {
        // Check if username already exists
        QueryWrapper<User> query = new QueryWrapper<>();
        query.eq("username", user.getUsername());
        if (userMapper.selectOne(query) != null) {
            return Result.fail(400, "用户名已存在");
        }
        // Encrypt password if provided
        if (user.getPassword() != null && !user.getPassword().isEmpty()) {
            user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        } else {
            return Result.fail(400, "密码不能为空");
        }
        // Set default role if not provided
        if (user.getRole() == null || user.getRole().isEmpty()) {
            user.setRole("普通员工");
        }
        // Set default status if not provided
        if (user.getStatus() == null || user.getStatus().isEmpty()) {
            user.setStatus("启用");
        }
        int insert = userMapper.insert(user);
        return insert > 0 ? Result.success(true) : Result.fail(500, "添加用户失败");
    }

    @Override
    public Result<Boolean> updateUser(User user) {
        if (user.getUserId() == null) {
            return Result.fail(400, "用户ID不能为空");
        }
        // If password is provided, encrypt it. Otherwise, do not update password.
//        if (user.getPassword() != null && !user.getPassword().isEmpty()) {
//            user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
//        } else {
//            // Prevent password from being updated to null or empty if not explicitly provided
//            user.setPassword(null);
//        }
        int update = userMapper.updateById(user);
        return update > 0 ? Result.success(true) : Result.fail(500, "更新用户失败");
    }

    @Override
    public Result<Boolean> deleteUser(Integer userId) {
        if (userId == null) {
            return Result.fail(400, "用户ID不能为空");
        }
        int delete = userMapper.deleteById(userId);
        return delete > 0 ? Result.success(true) : Result.fail(500, "删除用户失败");
    }

    @Override
    public Result<User> getUserById(Integer userId) {
        if (userId == null) {
            return Result.fail(400, "用户ID不能为空");
        }
        User user = userMapper.selectById(userId);
        return user != null ? Result.success(user) : Result.fail(404, "用户未找到");
    }
} 